﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Runtime.Messages;
using PServiceBus.Core.Manager;
using PServiceBus.Core.Runtime;
using PServiceBus.Core.Logger;

namespace PServiceBus.Core.Components {
    public class MessageStore : ComponentBase {

        private DefaultMessageHandler<PublishedMessage> _handler;

        public override void Init() {
            _handler = PublishedMessageManager.GetHandler();
            _handler.MessageReceived += (s, e) =>
            {
                foreach (var message in e.Messages) {
                    MethodHelper.TryLog(() => { 
                        PublishedMessageManager.Store(message);
                        message.Message.Delete();
                        message.Message = null;
                    });
                }
            };
            _handler.ErrorReceived += (s, e) =>
            {
                e.Continue = true;
                ESBLogger.Log(e.Error);
            };
            _handler.Start();
        }
        public override void Close() {
            if (_handler != null) _handler.Stop();
        }
        public override void Execute() {}
    }
}
